<template>
  <div class="rabbitmq-test-page">
    <div class="page-header">
      <h1>RabbitMQ压测工具</h1>
      <p>团队聊天室消息队列性能测试与监控</p>
    </div>

    <!-- 连接状态检查 -->
    <el-card class="test-section">
      <template #header>
        <div class="section-header">
          <span>连接状态检查</span>
          <el-button 
            type="primary" 
            size="small" 
            :loading="checking"
            @click="checkConnectionStatus"
          >
            检查状态
          </el-button>
        </div>
      </template>

      <div class="status-grid" v-if="connectionStatus">
        <div class="status-item">
          <span class="status-label">整体状态:</span>
          <el-tag :type="getOverallStatusType()">
            {{ connectionStatus.message || connectionStatus.status || '未知' }}
          </el-tag>
        </div>
        <div class="status-item">
          <span class="status-label">RabbitMQ连接:</span>
          <el-tag :type="connectionStatus.rabbitmq_available ? 'success' : 'danger'">
            {{ connectionStatus.rabbitmq_status || (connectionStatus.rabbitmq_available ? '已连接' : '未连接') }}
          </el-tag>
        </div>
        <div class="status-item">
          <span class="status-label">消息队列服务:</span>
          <el-tag :type="connectionStatus.message_queue_service ? 'success' : 'warning'">
            {{ connectionStatus.message_queue_service ? '已启用' : '未启用' }}
          </el-tag>
        </div>
        <div class="status-item">
          <span class="status-label">路由服务:</span>
          <el-tag :type="connectionStatus.routing_service ? 'success' : 'warning'">
            {{ connectionStatus.routing_service ? '已启用' : '未启用' }}
          </el-tag>
        </div>
        <div class="status-item">
          <span class="status-label">重试服务:</span>
          <el-tag :type="connectionStatus.retry_service ? 'success' : 'warning'">
            {{ connectionStatus.retry_service ? '已启用' : '未启用' }}
          </el-tag>
        </div>
        <div class="status-item">
          <span class="status-label">生产者服务:</span>
          <el-tag :type="connectionStatus.producer_service ? 'success' : 'warning'">
            {{ connectionStatus.producer_service ? '已启用' : '未启用' }}
          </el-tag>
        </div>
      </div>
    </el-card>

    <!-- 单条消息测试 -->
    <el-card class="test-section">
      <template #header>
        <span>单条消息发送测试</span>
      </template>

      <el-form :model="singleMessageForm" label-width="100px">
        <el-form-item label="团队ID">
          <el-input-number v-model="singleMessageForm.teamId" :min="1" />
        </el-form-item>
        <el-form-item label="消息内容">
          <el-input v-model="singleMessageForm.content" placeholder="输入测试消息内容" />
        </el-form-item>
        <el-form-item label="消息类型">
          <el-select v-model="singleMessageForm.messageType">
            <el-option label="文本" value="text" />
            <el-option label="图片" value="image" />
            <el-option label="文件" value="file" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button 
            type="primary" 
            :loading="sendingSingle"
            @click="sendSingleMessage"
          >
            发送测试消息
          </el-button>
        </el-form-item>
      </el-form>

      <div class="test-result" v-if="singleMessageResult">
        <h4>发送结果:</h4>
        <pre>{{ JSON.stringify(singleMessageResult, null, 2) }}</pre>
      </div>
    </el-card>

    <!-- 批量消息测试 -->
    <el-card class="test-section">
      <template #header>
        <span>批量消息发送测试（高并发）</span>
      </template>

      <el-form :model="batchMessageForm" label-width="100px">
        <el-form-item label="团队ID">
          <el-input-number v-model="batchMessageForm.teamId" :min="1" />
        </el-form-item>
        <el-form-item label="消息数量">
          <el-input-number v-model="batchMessageForm.messageCount" :min="1" :max="1000" />
        </el-form-item>
        <el-form-item label="并发数">
          <el-input-number v-model="batchMessageForm.concurrency" :min="1" :max="50" />
        </el-form-item>
        <el-form-item>
          <el-button 
            type="warning" 
            :loading="sendingBatch"
            @click="sendBatchMessages"
          >
            开始批量测试
          </el-button>
        </el-form-item>
      </el-form>

      <div class="test-result" v-if="batchMessageResult">
        <h4>批量测试结果:</h4>
        <div class="performance-stats">
          <div class="stat-item">
            <span class="stat-label">消息数量:</span>
            <span class="stat-value">{{ batchMessageResult.message_count }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">并发数:</span>
            <span class="stat-value">{{ batchMessageResult.concurrency }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">耗时:</span>
            <span class="stat-value">{{ batchMessageResult.duration_ms }}ms</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">吞吐量:</span>
            <span class="stat-value">{{ batchMessageResult.throughput_msg_per_sec?.toFixed(2) }} msg/s</span>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 系统监控 -->
    <el-card class="test-section">
      <template #header>
        <div class="section-header">
          <span>系统监控</span>
          <div>
            <el-button size="small" @click="loadHealthStatus">健康状态</el-button>
            <el-button size="small" @click="loadRoutingStats">路由统计</el-button>
            <el-button size="small" @click="loadRetryStats">重试统计</el-button>
            <el-button size="small" @click="loadDeadLetters">死信队列</el-button>
          </div>
        </div>
      </template>

      <el-tabs v-model="activeMonitorTab">
        <el-tab-pane label="健康状态" name="health">
          <div v-if="healthStatus">
            <pre>{{ JSON.stringify(healthStatus, null, 2) }}</pre>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="路由统计" name="routing">
          <div v-if="routingStats">
            <div class="stats-grid">
              <div v-for="(value, key) in routingStats" :key="key" class="stat-card">
                <div class="stat-title">{{ key }}</div>
                <div class="stat-number">{{ value }}</div>
              </div>
            </div>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="重试统计" name="retry">
          <div v-if="retryStats">
            <div class="stats-grid">
              <div v-for="(value, key) in retryStats" :key="key" class="stat-card">
                <div class="stat-title">{{ key }}</div>
                <div class="stat-number">{{ value }}</div>
              </div>
            </div>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="死信队列" name="deadletter">
          <div v-if="deadLetters">
            <div v-if="Object.keys(deadLetters.dead_letters || {}).length === 0">
              <el-empty description="暂无死信消息" />
            </div>
            <div v-else>
              <div v-for="(record, key) in deadLetters.dead_letters" :key="key" class="dead-letter-item">
                <div class="dead-letter-header">
                  <span class="message-key">{{ key }}</span>
                  <el-button 
                    size="small" 
                    type="primary"
                    @click="reprocessDeadLetter(key)"
                  >
                    重新处理
                  </el-button>
                </div>
                <div class="dead-letter-details">
                  <p><strong>团队ID:</strong> {{ record.message?.teamId }}</p>
                  <p><strong>发送者:</strong> {{ record.message?.senderId }}</p>
                  <p><strong>内容:</strong> {{ record.message?.content }}</p>
                  <p><strong>重试次数:</strong> {{ record.maxRetryCount }}</p>
                  <p><strong>最后错误:</strong> {{ record.lastException?.message }}</p>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button type="danger" @click="resetAllStats">重置所有统计</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { request } from '@/utils/request'

// 响应式数据
const checking = ref(false)
const connectionStatus = ref<any>(null)

const sendingSingle = ref(false)
const singleMessageForm = ref({
  teamId: 1,
  content: '这是一条测试消息',
  messageType: 'text'
})
const singleMessageResult = ref<any>(null)

const sendingBatch = ref(false)
const batchMessageForm = ref({
  teamId: 1,
  messageCount: 100,
  concurrency: 10
})
const batchMessageResult = ref<any>(null)

const activeMonitorTab = ref('health')
const healthStatus = ref<any>(null)
const routingStats = ref<any>(null)
const retryStats = ref<any>(null)
const deadLetters = ref<any>(null)

// 方法
const getOverallStatusType = () => {
  if (!connectionStatus.value) return 'info'
  const status = connectionStatus.value.status
  if (status === 'success') return 'success'
  if (status === 'warning') return 'warning'
  if (status === 'error') return 'danger'
  return 'info'
}

// 获取开发者会话令牌
const getDeveloperSessionToken = (): string | null => {
  return localStorage.getItem('developer_session_token')
}

// 创建带有开发者会话的请求配置
const createRequestConfig = () => {
  const sessionToken = getDeveloperSessionToken()
  if (!sessionToken) {
    throw new Error('开发者会话已过期，请重新认证')
  }

  return {
    headers: {
      'X-Developer-Session': sessionToken
    }
  }
}

const checkConnectionStatus = async () => {
  checking.value = true
  try {
    console.log('🔍 开始检查RabbitMQ连接状态...')
    const config = createRequestConfig()
    const data = await request.get('/test/rabbitmq/connection-status', config)

    console.log('📊 后端返回数据:', data)

    // 检查响应数据是否存在
    if (!data) {
      throw new Error('后端返回空数据')
    }

    connectionStatus.value = data

    // 更安全的状态检查
    const status = data.status || 'unknown'
    const message = data.message || ''

    if (status === 'success') {
      ElMessage.success(`连接状态检查完成: ${message}`)
    } else if (status === 'warning') {
      ElMessage.warning(`连接状态检查完成: ${message}`)
    } else if (status === 'error') {
      ElMessage.error(`连接状态检查失败: ${data.error || message || '未知错误'}`)
    } else {
      ElMessage.warning('连接状态检查完成，但状态未知')
    }
  } catch (error) {
    console.error('检查连接状态失败:', error)

    // 更详细的错误信息
    if (error.response) {
      console.error('错误响应状态:', error.response.status)
      console.error('错误响应数据:', error.response.data)
      ElMessage.error(`请求失败: ${error.response.status} - ${error.response.data?.message || error.message}`)
    } else if (error.request) {
      console.error('请求未收到响应:', error.request)
      ElMessage.error('网络错误：无法连接到后端服务')
    } else {
      console.error('请求配置错误:', error.message)
      ElMessage.error(`请求错误: ${error.message}`)
    }
  } finally {
    checking.value = false
  }
}

const sendSingleMessage = async () => {
  sendingSingle.value = true
  try {
    const config = createRequestConfig()
    const data = await request.post('/test/rabbitmq/send-message', null, {
      params: singleMessageForm.value,
      ...config
    })
    singleMessageResult.value = data

    if (data.status === 'success') {
      ElMessage.success('测试消息发送成功')
    } else {
      ElMessage.error('测试消息发送失败')
    }
  } catch (error) {
    console.error('发送测试消息失败:', error)
    ElMessage.error('发送测试消息失败')
  } finally {
    sendingSingle.value = false
  }
}

const sendBatchMessages = async () => {
  sendingBatch.value = true
  try {
    const data = await request.post('/test/rabbitmq/batch-send', null, {
      params: batchMessageForm.value
    })
    batchMessageResult.value = data

    if (data.status === 'success') {
      ElMessage.success('批量测试完成')
    } else {
      ElMessage.error('批量测试失败')
    }
  } catch (error) {
    console.error('批量测试失败:', error)
    ElMessage.error('批量测试失败')
  } finally {
    sendingBatch.value = false
  }
}

const loadHealthStatus = async () => {
  try {
    const data = await request.get('/test/rabbitmq/health-status')
    healthStatus.value = data
    activeMonitorTab.value = 'health'
  } catch (error) {
    console.error('加载健康状态失败:', error)
    ElMessage.error('加载健康状态失败')
  }
}

const loadRoutingStats = async () => {
  try {
    const data = await request.get('/test/rabbitmq/routing-stats')
    routingStats.value = data
    activeMonitorTab.value = 'routing'
  } catch (error) {
    console.error('加载路由统计失败:', error)
    ElMessage.error('加载路由统计失败')
  }
}

const loadRetryStats = async () => {
  try {
    const data = await request.get('/test/rabbitmq/retry-stats')
    retryStats.value = data
    activeMonitorTab.value = 'retry'
  } catch (error) {
    console.error('加载重试统计失败:', error)
    ElMessage.error('加载重试统计失败')
  }
}

const loadDeadLetters = async () => {
  try {
    const data = await request.get('/test/rabbitmq/dead-letters')
    deadLetters.value = data
    activeMonitorTab.value = 'deadletter'
  } catch (error) {
    console.error('加载死信队列失败:', error)
    ElMessage.error('加载死信队列失败')
  }
}

const reprocessDeadLetter = async (messageKey: string) => {
  try {
    const data = await request.post('/test/rabbitmq/reprocess-dead-letter', null, {
      params: { messageKey }
    })

    if (data.success) {
      ElMessage.success('死信消息重新处理成功')
      loadDeadLetters() // 刷新死信列表
    } else {
      ElMessage.error('死信消息重新处理失败')
    }
  } catch (error) {
    console.error('重新处理死信消息失败:', error)
    ElMessage.error('重新处理死信消息失败')
  }
}

const resetAllStats = async () => {
  try {
    await request.post('/test/rabbitmq/reset-stats')
    ElMessage.success('所有统计信息已重置')
    
    // 清空本地数据
    routingStats.value = null
    retryStats.value = null
    healthStatus.value = null
  } catch (error) {
    console.error('重置统计信息失败:', error)
    ElMessage.error('重置统计信息失败')
  }
}

// 页面加载时检查连接状态
onMounted(() => {
  checkConnectionStatus()
})
</script>

<style scoped lang="scss">
.rabbitmq-test-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 20px;
  
  h1 {
    margin: 0 0 8px 0;
    color: #303133;
  }
  
  p {
    margin: 0;
    color: #606266;
  }
}

.test-section {
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.status-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 8px;
  
  .status-label {
    font-weight: 500;
  }
}

.test-result {
  margin-top: 20px;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 4px;
  
  h4 {
    margin: 0 0 12px 0;
  }
  
  pre {
    margin: 0;
    font-size: 12px;
    line-height: 1.4;
  }
}

.performance-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 16px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
  
  .stat-label {
    font-size: 12px;
    color: #909399;
  }
  
  .stat-value {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 16px;
}

.stat-card {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  text-align: center;
  
  .stat-title {
    font-size: 12px;
    color: #666;
    margin-bottom: 8px;
  }
  
  .stat-number {
    font-size: 24px;
    font-weight: bold;
    color: #409eff;
  }
}

.dead-letter-item {
  margin-bottom: 16px;
  padding: 16px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
}

.dead-letter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  
  .message-key {
    font-weight: 600;
    color: #303133;
  }
}

.dead-letter-details {
  font-size: 14px;
  color: #606266;
  
  p {
    margin: 4px 0;
  }
}

.action-buttons {
  text-align: center;
  margin-top: 20px;
}
</style>
